import {
  login,
  logout,
  getInfo,
  code,
  updPassword,
	loginSuccess
} from '@/api/user'
import {
  getBackstage
} from '@/api/role'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import router, {
  resetRouter
} from '@/router'
import Vue from 'vue'
import hhframe from 'hhframe-web'
const defaultSettings = require('@/settings.js')

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  userinfo: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      code,
      codeKey,
	  remember
    } = userInfo
    const param = {
      'admin.username': username.trim(),
      'admin.password': password,
      'code': code,
      'codeKey': codeKey
    }
	if(remember) {
		param['remember'] = 'save_login'
	}
    return new Promise((resolve, reject) => {
      login(param).then(response => {
        // console.log('登录', response)
        commit('SET_TOKEN', response.data)
        setToken(response.data)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
	
	loginSuccess({
	  commit
	}, data) {
	  return new Promise((resolve, reject) => {
	    loginSuccess(data).then(response => {
	      // console.log('登录', response)
	      commit('SET_TOKEN', response.data)
	      setToken(response.data)
	      resolve(response)
	    }).catch(error => {
	      reject(error)
	    })
	  })
	},
	
	

  // get user code
  code({
    commit
  }) {
    return new Promise((resolve, reject) => {
      code().then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  

  // get user info
  getInfo({
    commit,
    state
  }) {
    // console.log(state.token)
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        // console.log(response)
        const data = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const {
          name,
          introduction
        } = data
        const avatar = data.headimg
        const roles = ['admin']
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
				
		Vue.use(hhframe, {
			mode: 'run',
			qiniu: {
			bucket_url: 'https://cdn.gexinit.com/', // 七牛存储空间地址
			// bucket_url: 'https://ykt.shandian001.com/', // 七牛存储空间地址
			token_url: process.env.VUE_APP_BASE_API + '/api/qiniu', // 七牛令牌生成地址
			flash_url: '/static/plug/qn_jssdk/plupload/Moxie.swf'
			},
			folder: {
			cate_add_url:  process.env.VUE_APP_BASE_API + '/system/plug/file/api/cate_add?user-token='+getToken(), // 创建分组（名称：name）
			cate_del_url:  process.env.VUE_APP_BASE_API + '/system/plug/file/api/cate_del?user-token='+getToken(), // 删除分组（分组ID：cid | 模式：mode -- 删除全部：all、仅删除分组：cate）
			cate_edit_url: process.env.VUE_APP_BASE_API + '/system/plug/file/api/cate_edit?user-token='+getToken(), // 修改分组名称（分组ID：cid | 名称：name）
			cate_list_url: process.env.VUE_APP_BASE_API + '/system/plug/file/api/getCateList?user-token='+getToken(), // 分组列表（无参数）
			file_add_url:  process.env.VUE_APP_BASE_API + '/system/plug/file/api/upfile?user-token='+getToken(), // 上传文件（分组ID：cate | 地址：url | 名称：name | 宽度：width | 高度：height | 大小：size | 类型：type）
			file_del_url:  process.env.VUE_APP_BASE_API + '/system/plug/file/api/file_del?user-token='+getToken(), // 删除文件（文件ID：files -- 多个文件以逗号隔开）
			file_edit_url: process.env.VUE_APP_BASE_API + '/system/plug/file/api/file_edit?user-token='+getToken(), // 修改文件分组（分组ID：cid | 文件ID：files -- 多个文件以逗号隔开）
			file_list_url: process.env.VUE_APP_BASE_API + '/system/plug/file/api/file_list?user-token='+getToken() // 文件列表（分组ID：cid | 文件类型：type | 分页：page | 每页数量：sizev
			}
		})
		
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user updPassword
  updPassword({
    commit,
    dispatch
  }, data) {
    return new Promise((resolve, reject) => {
      updPassword({
        oldPassword: data.currentPassword,
        password: data.newPassword
      }).then(response => {
        if (response.state) {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, {
            root: true
          })
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    // console.log(state.token)
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({
    commit,
    dispatch
  }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const {
        roles
      } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, {
        root: true
      })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
